const router = require("koa-router")();

/**
 *
 * api {get} /home/app/plugins/doc/api API接口文档
 *
 */
router.get("/doc/api", async (ctx, nex) => {
  const baas = ctx.baas;
  // 分组
  const groups = await BaaS.Models.class
    .query({ where: { baas_id: baas.id } })
    .fetchAll({
      withRelated: []
    });
  // 组权限
  const classAuths = await BaaS.Models.class_auth
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchAll({
      withRelated: ["auth"]
    });
  // 表权限
  const classTables = await BaaS.Models.class_table
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchAll({
      withRelated: ["auth"]
    });
  // 模型
  const models = await BaaS.Models.table
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchAll({
      withRelated: []
    });
  // 关联
  const relations = await BaaS.Models.relation
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchAll({
      withRelated: []
    });
  // 字段
  const fields = await BaaS.Models.class_field
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchAll({
      withRelated: []
    });

  const data = [];
  for (const group of groups) {
    group.headers = {
      "x-qingful-appid": baas.appid,
      "x-qingful-appkey": baas.appkey,
      "x-qingful-dev": true
    };
    group.auth = [];
    for (const classAuth of classAuths) {
      if (classAuth.class_id == group.id) {
        group.auth.push(classAuth.auth);
        group.headers[classAuth.auth.name] = "";
      }
    }
    const tableData = [];

    for (const classTable of classTables) {
      if (classTable.class_id == group.id) {
        classTable.api = [];
        if (classTable.table == "baas.file") {
          classTable.api.push({
            api: `https://baas.qingful.com/2.0/class/${
              group.name
            }/image/upload`,
            headers: group.headers,
            mag: "上传图片",
            method: "POST"
          });
        } else {
          for (const classAuth of classAuths) {
            if (classAuth.class_id == group.id) {
              classTable.api.push({
                api: `https://baas.qingful.com/2.0/class/${group.name}/verify/${
                  classAuth.auth.name
                }`,
                headers: group.headers,
                mag: `解密数据${classAuth.auth.name}`,
                method: "GET"
              });
            }
          }
        }

        classTable.fields = [];
        if (classTable.table != "baas.file") {
          classTable.fields = await ctx.fields(baas.database, classTable.table);
        }

        // 查询
        if (classTable.fetch && classTable.table != "baas.file") {
          const fetchTips = [];
          const fetchAllTips = [];
          const fetchPageTips = [];
          // 密钥
          if (classTable.auth) {
            fetchTips.push(`将返回由密钥${classTable.auth.name}加密的字符串`);
          }
          // 模型
          for (const model of models) {
            if (model.name == classTable.table && model.hidden) {
              const msg = `隐藏字段：${model.hidden}`;
              fetchTips.push(msg);
              fetchAllTips.push(msg);
              fetchPageTips.push(msg);
            }
          }
          // 关联
          // classTable.relations = [];
          for (const relation of relations) {
            if (relation.table == classTable.table) {
              // classTable.relations.push(relation);
              const msg = `关联关系:数据表(${relation.table})关联表(${
                relation.target
              })关联昵称(${relation.targeted})关联关系(${
                relation.relation
              })外键(${relation.foreign_key})`;
              fetchTips.push(msg);
              fetchAllTips.push(msg);
              fetchPageTips.push(msg);
            }
          }
          classTable.api.push({
            api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
              classTable.table
            }/fetch`,
            headers: group.headers,
            mag: "查询一条数据",
            method: "GET",
            tips: fetchTips
          });
          if (!classTable.auth) {
            classTable.api.push({
              api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
                classTable.table
              }/fetchAll`,
              headers: group.headers,
              mag: "查询多条数据",
              method: "GET",
              tips: fetchAllTips
            });
            classTable.api.push({
              api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
                classTable.table
              }/fetchPage`,
              headers: group.headers,
              mag: "查询分页数据",
              method: "GET",
              tips: fetchPageTips
            });
          }
        }
        // 新增
        if (classTable.add && classTable.table != "baas.file") {
          const addTips = [];
          const saveTips = [];
          // 模型
          for (const model of models) {
            if (model.name == classTable.table && model.unique) {
              if (model.unique) {
                addTips.push(`唯一字段：${model.unique}`);
                saveTips.push(`唯一字段：${model.unique}`);
              }
              if (model.uuid) {
                addTips.push("自增主键为uuid");
                saveTips.push("自增主键为uuid");
              }
            }
          }
          for (const field of fields) {
            if (field.class_id == group.id && field.table == classTable.table) {
              addTips.push(
                `字段(${field.table})值(${field.value})类型(${
                  field.type
                })客户端是否需要传值(${field.required ? "是" : "否"})`
              );
            }
          }
          classTable.api.push({
            api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
              classTable.table
            }/add`,
            headers: group.headers,
            mag: "新增数据",
            method: "POST",
            tips: addTips
          });
          classTable.api.push({
            api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
              classTable.table
            }/save`,
            headers: group.headers,
            mag: "新增数据",
            method: "POST",
            tips: saveTips
          });
        }

        // 更新
        if (classTable.update && classTable.table != "baas.file") {
          const updateTips = [];
          for (const field of fields) {
            if (field.class_id == group.id && field.table == classTable.table) {
              updateTips.push(
                `字段(${field.table})值(${field.value})类型(${
                  field.type
                })客户端是否需要传值(${field.required ? "是" : "否"})`
              );
            }
          }
          classTable.api.push({
            api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
              classTable.table
            }/update`,
            headers: group.headers,
            mag: "更新数据",
            method: "POST",
            tips: updateTips
          });
        }

        // 删除
        if (classTable.delete && classTable.table != "baas.file") {
          classTable.api.push({
            api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
              classTable.table
            }/del`,
            headers: group.headers,
            mag: "删除数据",
            method: "GET",
            tips: []
          });
          classTable.api.push({
            api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
              classTable.table
            }/delete`,
            headers: group.headers,
            mag: "删除数据",
            method: "GET",
            tips: []
          });
          classTable.api.push({
            api: `https://baas.qingful.com/2.0/class/${group.name}/table/${
              classTable.table
            }/destroy`,
            headers: group.headers,
            mag: "删除数据",
            method: "GET",
            tips: []
          });
        }

        tableData.push({
          name: classTable.table,
          api: classTable.api,
          fields: classTable.fields
        });
      }
    }

    data.push({
      class: group.name,
      auth: group.auth,
      headers: group.headers,
      table: tableData
    });
  }

  const method = [
    "where",
    "orWhere",
    "whereNot",
    "orWhereNot",
    "whereIn",
    "orWhereIn",
    "whereNotIn",
    "orWhereNotIn",
    "whereNull",
    "orWhereNull",
    "whereNotNull",
    "orWhereNotNull",
    "whereBetween",
    "whereNotBetween",
    "orWhereBetween",
    "orWhereNotBetween",
    "limit",
    "offset",
    "orderBy",
    "column",
    "count",
    "sum",
    "min",
    "max",
    "avg",
    "page",
    "pageSize",
    "deleted",
    "forceDelete",
    "related",
    "joined",
    "join",
    "innerJoin",
    "leftJoin",
    "leftOuterJoin",
    "rightJoin",
    "rightOuterJoin",
    "outerJoin",
    "fullOuterJoin",
    "crossJoin"
  ];

  ctx.success({ data: data, method: method }, "api接口");
});
// 云函数
router.get("/doc/function", async (ctx, nex) => {
  const baas = ctx.baas;
  const userBaas = await BaaS.Models.user_baas
    .query({ where: { baas_id: baas.id } })
    .fetch();
  // 分组
  const groups = await BaaS.Models.class
    .query({ where: { baas_id: baas.id } })
    .fetchAll({
      withRelated: []
    });
  // 云函数
  const functions = await BaaS.Models.function
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
    })
    .fetchAll({
      withRelated: ["class"]
    });
  // 如果引擎关闭，删除函数列表
  if (!userBaas.engine) {
    // functions.splice(0, functions.length);
  }
  // 组权限
  const classAuths = await BaaS.Models.class_auth
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchAll({
      withRelated: ["auth"]
    });

  const data = [];
  const headers = {
    "x-qingful-appid": baas.appid,
    "x-qingful-appkey": baas.appkey,
    "x-qingful-dev": true
  };
  for (const group of groups) {
    const fun = [];
    for (const row of functions) {
      row.auth = [];
      row.headers = {
        "x-qingful-appid": baas.appid,
        "x-qingful-appkey": baas.appkey,
        "x-qingful-dev": true
      };
      for (const classAuth of classAuths) {
        if (row.class_id == classAuth.class_id) {
          row.headers[classAuth.auth.name] = "";
          row.auth.push(classAuth.auth);
        }
      }
      row.api = `https://baas.qingful.com/2.0/class/${
        row.class.name
      }/function/${row.name}`;
      if (group.id == row.class_id) {
        fun.push(row);
      }
    }
    data.push({
      class: group.name,
      functions: fun
    });
  }

  ctx.success(data, "云函数接口");
});

module.exports = router;
